/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-10-31 09:57:42
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-11-03 12:02:17
 * @FilePath: /Learn/WebCalculator/TcpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include "Log.hpp"
#include "Socket.hpp"
#include <signal.h>
#include <functional>

using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
        : _port(port), _callback(callback)
    {
    }

    bool InitServer()
    {
        _listenfd.Socket();
        _listenfd.Bind(_port);
        _listenfd.Listen();
        lg(Info, "init server ... done");
        return true;
    }

    void Start()
    {
        // 系统自动回收子进程
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = _listenfd.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "accept a new link,sockfd:%d,clientip:%s,clientport:%d", sockfd, clientip.c_str(), clientport);
            // 提供服务
            if (fork() == 0)
            {
                _listenfd.Close();
                std::string inbuffer_stream;
                // 数据计算
                while (true)
                {
                    char buffer[1280];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = '\0';
                        inbuffer_stream += buffer;
                        lg(Debug, "debug:\n%s", inbuffer_stream.c_str());

                        while (true)
                        {
                            // 要发送给客户端的内容
                            std::string info = _callback(inbuffer_stream);
                            // 若输入的内容不合协议，则直接continue
                            if (info.empty())
                                break;
                            lg(Debug,"debug,response:\n%s",info.c_str());
                            lg(Debug,"debug:\n%s",inbuffer_stream.c_str());
                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else if (n == 0)
                        break;
                    else
                        break;
                }

                exit(0);
            }
            close(sockfd);
        }
    }

    ~TcpServer()
    {
    }

private:
    Sock _listenfd;
    uint16_t _port;
    func_t _callback;
};